package Experiment;
/**
 * 1从buyJava。jsp页面获取到要购买Java的数量，然后写入数据库的表中
 * 2查看购物车
 * 3.删除是全部删除，或者是更新数据库
 */

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class newCarGet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置服务器端以UTF-8编码进行输出
        resp.setCharacterEncoding("UTF-8");
        //设置浏览器以UTF-8编码进行接收,解决中文乱码问题
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String Num = req.getParameter("num");
        String name = req.getParameter("Java");
        name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
        try {
            try {
                String url = "jdbc:sqlserver://localhost:1433;DataBaseName=Login;integratedSecurity=true;";
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                Connection comm = DriverManager.getConnection(url);
                if (name.equals("java")) {
                    String sql = "update Book set bookNO=('" + Num + "') where bookName='java'";
                    Statement st = comm.createStatement();
                    //5 执行sql语句
                    int temp = st.executeUpdate(sql);
                    System.out.println("返回的值：" + temp);
                    //6 关闭sql对象
                    st.close();
                    //7 关闭连接
                    comm.close();
                    out.println("购买成功！，将在3s内返回商品页面。");
                    resp.setHeader("refresh", "3,http://localhost:8080/javaWeb_war_exploded/market.jsp");
                } else {
                    String sql = "update Book set bookNO=('" + Num + "') where bookName='C++'";
                    Statement st = comm.createStatement();
                    //5 执行sql语句
                    int temp = st.executeUpdate(sql);
                    System.out.println("返回的值：" + temp);
                    //6 关闭sql对象
                    st.close();
                    //7 关闭连接
                    comm.close();
                    out.println("购买成功！，将在3s内返回商品页面。");
                    resp.setHeader("refresh", "3,http://localhost:8080/javaWeb_war_exploded/market.jsp");
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
